<template>
  <div class="app-container" style="height: 100%">
    <div class="nav">
      <el-tabs class="demo-tabs" v-model="activeName" @tab-change="tabClick">
        <el-tab-pane v-for="item in tabPanes" :key="item.value" :name="item.value">
          <template #label>
            <span>{{ item.label }}</span>
          </template>
        </el-tab-pane>
      </el-tabs>
    </div>

    <div class="app-container-inner" v-loading="loading" element-loading-text="加载中...">
      <div class="header_search">
        <div class="flex-align-center" style="gap: 5px; margin-bottom: 10px">
          <HPlainButton @click="addWithdrawalShow">新增提现单</HPlainButton>
          <HPlainButton :disabled="withdrawVo.ids.length == 0" @click="handleMultiplePaymentClick">
            批量打款
          </HPlainButton>
          <HPlainButton :disabled="withdrawVo.ids.length == 0" @click="dialogChackVisibleShow">
            批量审核
          </HPlainButton>
          <HButton @click="onShowExport"> 导出 </HButton>
        </div>
        <div
          style="
            margin-bottom: 10px;
            display: flex;
            justify-content: flex-end;
            align-items: center;
            flex-wrap: wrap;
            row-gap: 10px;
          "
        >
          <el-select
            class="input-item mr5"
            v-model="ListData.dateType"
            placeholder="选择时间"
            clearable
            @change="ListData.dateType == 5 ? '' : getList()"
          >
            <el-option
              v-for="item in timeOptions"
              :key="item.value"
              :value="item.value"
              :label="item.title"
            />
          </el-select>
          <div class="select-time mr5" v-if="ListData.dateType == 5">
            <el-date-picker
              v-model="valValue"
              type="daterange"
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="dateChange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </div>
          <el-select
            @change="getList"
            v-model="ListData.networkId"
            :loading="loading"
            :filter-method="getNetworkPageSelectList"
            class="input-item mr5"
            clearable
            filterable
            placeholder="请选择服务商"
            remote-show-suffix
          >
            <el-option
              v-for="item in networkSelectData"
              :key="item.name"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-input
            v-model.trim="ListData.engineer"
            placeholder="工程师"
            class="input-with"
            clearable
            @keyup.enter="getList"
            @clear="getList"
          />
          <el-input
            v-model.trim="ListData.workNo"
            placeholder="工单单号"
            class="input-with"
            clearable
            @keyup.enter="getList"
            @clear="getList"
          />
          <el-input
            v-model.trim="ListData.keyword"
            placeholder="提现单号"
            class="input-with"
            clearable
            @keyup.enter="getList"
            @clear="getList"
          />
          <div style="display: flex; gap: 5px">
            <HButton type="primary" @click="getList">
              <el-icon class="mr5">
                <Search />
              </el-icon>
              搜索
            </HButton>
            <HButton @click="handleResetClick">
              <el-icon class="mr5">
                <RefreshRight />
              </el-icon>
              重置
            </HButton>
          </div>
        </div>
      </div>
      <div class="table">
        <el-table
          :border="true"
          stripe
          resizable
          :data="tableData"
          :summary-method="(val) => getSummaries(val, [1, 5, 6, 7])"
          show-summary
          ref="tableInstance"
          height="100%"
          @selection-change="handleTableSelect"
          style="position: absolute"
        >
          <!-- 选择 -->
          <el-table-column type="selection" width="40" fixed />

          <!-- 序号 -->
          <el-table-column type="index" label="序号" fixed width="50" />

          <!-- 提现单号 -->
          <el-table-column show-overflow-tooltip prop="code" label="提现单号" fixed min-width="120">
            <template #default="{ row }">
              <span class="xy_main_btn" @click="withdrawalDetailShow(row.id)">
                {{ row.code }}
              </span>
            </template>
          </el-table-column>

          <!-- 关联单号 -->
          <el-table-column show-overflow-tooltip prop="workNo" label="关联工单" min-width="150">
            <template #default="{ row }">
              <span>
                {{ row.workNo.length == 1 ? row.workNo[0] : row.workNo.length + '张关联工单' }}
              </span>
            </template>
          </el-table-column>

          <!-- 申请时间 -->
          <el-table-column prop="createTime" label="申请时间" sortable width="128" />

          <!-- 工程师 -->
          <el-table-column
            show-overflow-tooltip
            prop="applyNetworkEmp"
            label="工程师"
            min-width="130"
          />

          <!-- 服务商 -->
          <el-table-column show-overflow-tooltip prop="network" label="服务商" min-width="130" />

          <!-- 状态 -->
          <el-table-column
            :align="'center'"
            show-overflow-tooltip
            prop="status"
            :filters="[
              { text: '提现审核', value: 1 },
              { text: '等待打款', value: 2 },
              { text: '已推送银行', value: 3 },
              { text: '已驳回', value: 5 },
              { text: '推送中', value: 88 },
              { text: '推送失败', value: 99 },
            ]"
            :filter-method="filterTag"
            filter-placement="bottom-end"
            label="状态"
            min-width="90"
          >
            <template #default="{ row }">
              <HStatus type="warning" v-if="row.status === 1">提现审核</HStatus>
              <HStatus type="warning" v-if="row.status === 2">等待打款</HStatus>
              <HStatus type="success" v-if="row.status === 3">已推送银行</HStatus>
              <!-- <HStatus type="error" v-if="scope.row.status === 4">失败</HStatus> -->
              <HStatus type="error" v-if="row.status === 5">已驳回</HStatus>
              <HStatus type="warning" v-if="row.status === 88">推送中 </HStatus>
              <HStatus type="error" v-if="row.status === 99">推送失败</HStatus>
            </template>
          </el-table-column>

          <el-table-column
            show-overflow-tooltip
            :align="'right'"
            prop="failReason"
            label="推送失败原因"
            min-width="110"
          >
          </el-table-column>

          <!-- 总提现金额 -->
          <el-table-column
            show-overflow-tooltip
            :align="'right'"
            prop="withdrawMoney"
            label="总提现金额"
            min-width="110"
          >
            <template #default="{ row }"> ￥{{ (row.withdrawMoney || 0).toFixed(2) }} </template>
          </el-table-column>

          <!-- 总手续费 -->
          <el-table-column
            show-overflow-tooltip
            :align="'right'"
            prop="withdrawHandlingFee"
            label="总手续费"
            min-width="110"
          >
            <template #default="{ row }">
              ￥{{ (row.withdrawHandlingFee || 0).toFixed(2) }}
            </template>
          </el-table-column>

          <!-- 到账金额 -->
          <el-table-column
            show-overflow-tooltip
            :align="'right'"
            prop="receivedAmount"
            label="到账金额"
            min-width="110"
          >
            <template #default="{ row }">
              <span :style="{ color: row.status == 2 ? 'rgba(255, 0, 0, 1)' : '' }">
                ￥{{ (row.receivedAmount || 0).toFixed(2) }}
              </span>
            </template>
          </el-table-column>

          <!-- 提现银行 -->
          <el-table-column show-overflow-tooltip prop="name" label="提现银行" min-width="130" />
          <!-- <el-table-column show-overflow-tooltip prop="openingBank" label="开户行" min-width="130" /> -->

          <!-- 收款人姓名 -->
          <el-table-column
            show-overflow-tooltip
            prop="cardholderName"
            label="收款人姓名"
            min-width="130"
          />
          <el-table-column show-overflow-tooltip prop="bankNo" label="收款账户" min-width="130">
            <template #default="{ row }">
              <span style="display: flex; justify-content: space-between; align-items: center">
                <span v-if="row.isShow"> {{ row.bankNo }}</span>
                <span v-else>
                  {{ '***'.repeat(4) + row.bankNo.substring(row.bankNo.length - 4) }}</span
                >
                <el-icon
                  style="cursor: pointer"
                  color="#007cff"
                  v-if="row.isShow"
                  @click="row.isShow = false"
                >
                  <View />
                </el-icon>
                <el-icon color="#007cff" style="cursor: pointer" @click="row.isShow = true" v-else>
                  <Hide />
                </el-icon>
              </span>
            </template>
          </el-table-column>

          <!-- 审核时间 -->
          <el-table-column show-overflow-tooltip prop="checkTime" label="审核时间" width="130" />

          <!-- 备注 -->
          <el-table-column show-overflow-tooltip prop="applyRemark" label="备注" width="120" />

          <!-- 操作 -->
          <el-table-column
            fixed="right"
            :align="'center'"
            show-overflow-tooltip
            label="操作"
            width="80"
          >
            <template v-slot="{ row }">
              <el-space :size="0" :spacer="spacer">
                <HLink v-if="row.status === 1" @click="handleCheckClick(row.id)">审核</HLink>
                <HLink v-if="row.status === 2" @click="handlePaymentClick(row)"> 打款 </HLink>
                <HLink v-if="row.status === 99" @click="handlePaymentClick(row)"> 重新打款 </HLink>
              </el-space>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="footer">
        <Pagination
          ref="paginationInstance"
          :list_total="total"
          @size-change="getList"
          @current-change="getList"
        />
      </div>
    </div>

    <!-- 新增提现单 -->
    <el-drawer
      title="新增提现单"
      v-model="withdrawalAddDialog"
      size="80%"
      @close="onCancel"
      @click="visibleSearchBank = false"
    >
      <div
        class="add-dialog"
        @click="visibleSearchBank = false"
        v-loading="saveLoading"
        element-loading-text="加载中..."
      >
        <h4 class="title_top">基本信息</h4>
        <el-form
          label-position="right"
          ref="formRef"
          :rules="rules"
          style="margin: 24px 0"
          :model="ruleForm"
          label-width="auto"
          @validate="handleFormValidate"
        >
          <div class="add_withdrawal_form_content">
            <div class="modal_form_content">
              <el-form-item
                label="工程师"
                prop="applyNetworkEmpId"
                :class="{
                  form_select_item: true,
                  error_form_item: !formValidateResult['applyNetworkEmpId'],
                }"
              >
                <el-select
                  v-model="ruleForm.applyNetworkEmpId"
                  :filter-method="handleapplyNetworkEmpIdOptions"
                  filterable
                  placeholder="请选择"
                  remote-show-suffix
                  style="max-width: 220px"
                >
                  <el-option
                    v-for="item in appEmpList"
                    @click="onClickEmp(item)"
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="关联服务商"
                prop="applyNetworkId"
                :class="{
                  form_select_item: true,
                  error_form_item: !formValidateResult['applyNetworkId'],
                }"
              >
                <el-select
                  v-model="ruleForm.applyNetworkId"
                  placeholder="请选择"
                  style="max-width: 220px"
                >
                  <el-option
                    v-for="item in networkList"
                    @click="networkChange(item.id)"
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="手续费方式" class="form_input_item">
                <el-input
                  disabled
                  :model-value="`${
                    ruleForm.withdrawHandlingFeeStrategy == 1
                      ? '按总单提现金额的' + ruleForm.handingFeeProportion + '%'
                      : '按每单' + ruleForm.handingFeeFixedOrder + '元'
                  }`"
                  style="max-width: 220px"
                />
              </el-form-item>
            </div>
            <div class="modal_form_content">
              <el-form-item
                label="银行卡"
                prop="name"
                :class="{
                  form_input_item: true,
                  error_form_item: !formValidateResult['name'],
                }"
              >
                <el-popover
                  ref="popoverInputRef"
                  popper-class="monitor-yt-popover"
                  :width="240"
                  :visible="visibleSearchBank"
                  placement="bottom"
                >
                  <div style="max-height: 380px; overflow: auto">
                    <div
                      class="user_item"
                      @click="changebankCardItem(item)"
                      v-for="(item, index) in bankCardList"
                      :value="item.id"
                      :label="item.phone"
                      :item="item"
                      :key="index"
                      >{{ item.name }} &nbsp;({{ item.code.slice(-4) }})
                    </div>
                  </div>
                  <template #reference>
                    <el-input
                      @click="getNetworkBandSelectList"
                      style="max-width: 220px"
                      maxlength="30"
                      placeholder="银行卡"
                      v-model="ruleForm.name"
                      clearable
                    />
                  </template>
                </el-popover>
              </el-form-item>
              <el-form-item
                label="银行卡号"
                prop="bankNo"
                :class="{
                  form_input_item: true,
                  error_form_item: !formValidateResult['bankNo'],
                }"
              >
                <el-input
                  placeholder="银行卡号"
                  style="max-width: 220px"
                  @input="ruleForm.bankNo = autoFixedDicimal(ruleForm.bankNo)"
                  maxlength="19"
                  v-model="ruleForm.bankNo"
                  clearable
                  disabled
                />
              </el-form-item>
              <el-form-item
                label="持卡人姓名"
                prop="cardholderName"
                :class="{
                  form_input_item: true,
                  error_form_item: !formValidateResult['cardholderName'],
                }"
              >
                <el-input
                  placeholder="持卡人姓名"
                  style="max-width: 220px"
                  maxlength="30"
                  v-model="ruleForm.cardholderName"
                  clearable
                  disabled
                />
              </el-form-item>
            </div>
            <div class="modal_form_content">
              <!-- 银行行号 -->
              <el-form-item label="银行行号" prop="bankCode" class="form_input_item">
                <el-input disabled placeholder="请输入银行行号" :model-value="ruleForm.bankCode" />
              </el-form-item>

              <!-- 开户网点 -->
              <el-form-item label="开户网点" prop="openAccountBankNetwork" class="form_input_item">
                <el-input
                  placeholder="请输入开户网点"
                  disabled
                  :model-value="ruleForm.openAccountBankNetwork"
                />
              </el-form-item>
              <el-form-item
                label="申请备注"
                prop="applyRemark"
                class="form_textarea_item apply_reamrk"
              >
                <el-input
                  v-model="ruleForm.applyRemark"
                  maxlength="100"
                  type="textarea"
                  placeholder="请输入备注"
                  show-word-limit
                  resize="both"
                />
              </el-form-item>
            </div>
          </div>
        </el-form>
        <div style="display: flex; align-items: center; gap: 12px">
          <h4 class="title_top">工单信息</h4>
          <HPlainButton @click="onShowUpgrade" :height="22" :padding-lr="6">选择工单</HPlainButton>
        </div>
        <el-table
          height="600"
          :border="true"
          :summary-method="(val) => getSummaries(val, [0, 2, 3, 4])"
          :data="ruleForm.orderVos"
          show-summary
          resizable
          stripe
          style="margin-top: 12px"
        >
          <el-table-column
            fixed="left"
            align="center"
            label="序号"
            width="70"
            show-overflow-tooltip
          >
            <template v-slot="i">
              <div class="flex-center">
                <div class="index_tip">{{ i.$index + 1 }}</div>
                <div class="delete" @click="deleteItem(i.row)">
                  <el-icon color="rgba(245, 108, 108, 1)" size="16" class="dele-icon">
                    <RemoveFilled />
                  </el-icon>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="关联工单" prop="workNo" min-width="50" show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="可提现金额"
            prop="oldWithdrawMoney"
            min-width="50"
            show-overflow-tooltip
          >
            <template v-slot="i"> ￥{{ (i.row.oldWithdrawMoney || 0).toFixed(2) }} </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="手续费"
            prop="money"
            min-width="50"
            show-overflow-tooltip
          >
            <template v-slot="i"> ￥{{ (i.row.money || 0).toFixed(2) }} </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="实际到账"
            prop="withdrawMoney"
            min-width="50"
            show-overflow-tooltip
          >
            <template v-slot="i"> ￥{{ (i.row.withdrawMoney || 0).toFixed(2) }} </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div style="display: flex; gap: 10px; justify-content: flex-end">
          <HButton is-modal type="primary" @click="submitSave"> 提交 </HButton>
          <HButton is-modal @click="onCloseAddWithdrawal">取消</HButton>
        </div>
      </template>
    </el-drawer>
    <!-- end -->

    <!-- 审核提现单 -->
    <el-drawer title="审核提现单" v-model="withdrawalCheckDialog" size="80%">
      <div class="check-dialog">
        <h4 class="title_top">基本信息</h4>
        <el-form
          label-position="right"
          ref="formRef"
          :model="ruleForm"
          :data="withdrawalDetail"
          label-width="80"
          style="margin: 16px 0 10px 0"
        >
          <div class="check_withdrawal_basic_info">
            <div class="only_show_info_form_content">
              <el-form-item label="提现单号:" class="form_item">{{
                withdrawalDetail?.code
              }}</el-form-item>
              <el-form-item label="工程师:" class="form_item">{{
                withdrawalDetail?.applyNetworkEmp
              }}</el-form-item>
              <el-form-item label="提现状态:" class="form_item">
                <HStatus type="warning" v-if="withdrawalDetail?.status === 1">提现审核</HStatus>
                <HStatus type="warning" v-if="withdrawalDetail?.status === 2">等待打款</HStatus>
                <HStatus type="success" v-if="withdrawalDetail?.status === 3">已推送银行</HStatus>
                <HStatus type="error" v-if="withdrawalDetail?.status === 4">失败</HStatus>
                <HStatus color="#7948ea" v-if="withdrawalDetail?.status === 5">已驳回</HStatus>
                <HStatus type="warning" v-if="withdrawalDetail?.status === 88">推送中</HStatus>
                <HStatus type="error" v-if="withdrawalDetail?.status === 99">推送失败</HStatus>
              </el-form-item>
            </div>
            <div class="only_show_info_form_content">
              <el-form-item label="银行账户:" class="form_item">{{
                withdrawalDetail?.bankNo
              }}</el-form-item>
              <el-form-item label="提现银行:" class="form_item">{{
                withdrawalDetail?.name
              }}</el-form-item>
              <!-- <el-form-item label="开户行:">{{ withdrawalDetail?.openingBank }}</el-form-item> -->
              <el-form-item label="收款人姓名:" class="form_item">{{
                withdrawalDetail?.cardholderName
              }}</el-form-item>
            </div>
            <div class="only_show_info_form_content">
              <el-form-item label="申请时间:" class="form_item">{{
                withdrawalDetail?.createTime
              }}</el-form-item>
              <el-form-item label="申请备注:" class="form_item">{{
                withdrawalDetail?.applyRemark
              }}</el-form-item>
              <el-form-item label="审核备注:" class="reamrk_form_item">
                <el-input
                  v-model="checkWithdrawVo.checkRemark"
                  type="textarea"
                  placeholder="请输入备注"
                  maxlength="100"
                  show-word-limit
                  resize="both"
                />
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>
      <el-tabs v-model="activeNameCheck">
        <el-tab-pane :label="`关联工单(${ruleForm.orderVos.length})`" name="first">
          <!-- <el-table height="240" :border="true" :summary-method="(val) => getSummaries(val, [2, 3, 4])"
            :data="WithdrawOrderList" show-summary resizable stripe style="margin-top: 12px">
            <el-table-column fixed="left" type="index" align="center" label="序号" width="50" show-overflow-tooltip>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="workNo" label="关联工单" min-width="90">
              <template v-slot="i">
                <span class="xy_main_btn" @click="pageGo(i.row.workId),withdrawalCheckDialog=false">{{ i.row.workNo }}</span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="可提现金额" prop="oldWithdrawMoney" min-width="100" show-overflow-tooltip>
              <template v-slot="i"> ￥{{ (i.row.oldWithdrawMoney || 0).toFixed(2) }} </template>
            </el-table-column>
            <el-table-column fixed="right" label="手续费" prop="money" min-width="90" show-overflow-tooltip>
              <template v-slot="i"> ￥{{ (i.row.money || 0).toFixed(2) }} </template>
            </el-table-column>
            <el-table-column fixed="right" label="实际到账" prop="withdrawMoney" min-width="90" show-overflow-tooltip>
              <template v-slot="i"> ￥{{ (i.row.withdrawMoney || 0).toFixed(2) }} </template>
            </el-table-column>
          </el-table> -->
          <el-table
            height="550"
            :border="true"
            :summary-method="(val) => getSummaries(val, [0, 2, 3, 4, 5])"
            :data="ruleForm.orderVos"
            show-summary
            resizable
            stripe
            style="margin-top: 12px"
          >
            <el-table-column
              fixed="left"
              type="index"
              align="center"
              label="序号"
              width="50"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="workNo" label="关联工单" min-width="90">
              <template v-slot="i">
                <span
                  class="xy_main_btn"
                  @click="pageGo(i.row.workId), (withdrawalEditVisible = false)"
                  >{{ i.row.workNo }}</span
                >
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="原工单金额"
              prop="oldWithdrawMoney"
              min-width="100"
              show-overflow-tooltip
            >
              <template v-slot="i"> ￥{{ (i.row.oldWithdrawMoney || 0).toFixed(2) }} </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="修改后工单金额"
              prop="withdrawMoney"
              min-width="100"
              show-overflow-tooltip
            >
              <template v-slot="i">
                <el-input
                  v-model="i.row.withdrawMoney"
                  @change="changeInput(i.row)"
                  style="max-width: 220px"
                  @input="i.row.withdrawMoney = autoFixedDicimal(i.row.withdrawMoney)"
                >
                  <template #prepend> ￥ </template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="手续费"
              prop="money"
              min-width="90"
              show-overflow-tooltip
            >
              <template v-slot="i"> ￥{{ (i.row.money || 0).toFixed(2) }} </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="实际到账"
              prop="withdrawMoney_o"
              min-width="90"
              show-overflow-tooltip
            >
              <template v-slot="i"> ￥{{ (i.row.withdrawMoney_o || 0).toFixed(2) }} </template>
            </el-table-column>
          </el-table>
          <div class="footer" style="margin-top: 12px">
            <el-pagination
              v-model:current-page="page"
              background
              v-model:page-size="size"
              :page-sizes="[10, 20, 30, 50]"
              :size="size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="ruleForm.orderVos.length"
              @size-change="pageSize"
              @current-change="pageCurr"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane label="操作日志" name="second">
          <el-table
            height="540"
            :border="true"
            :data="WithdrawLogList"
            resizable
            stripe
            style="margin-bottom: 12px"
          >
            <el-table-column
              fixed="left"
              type="index"
              align="center"
              label="序号"
              width="50"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="event" label="操作内容" min-width="90">
            </el-table-column>
            <el-table-column label="操作人" prop="applyEmp" min-width="100" show-overflow-tooltip>
            </el-table-column>
            <!-- <el-table-column fixed="right" label="关联服务商" prop="network" min-width="90" show-overflow-tooltip> -->
            <!-- </el-table-column> -->
            <el-table-column
              fixed="right"
              label="备注"
              prop="remark"
              min-width="110"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作时间"
              prop="createTime"
              width="130"
              show-overflow-tooltip
            >
            </el-table-column>
          </el-table>
          <div class="footer">
            <Pagination
              ref="paginationLogRef"
              :list_total="totalLog"
              @size-change="getWithdrawLogList()"
              @current-change="getWithdrawLogList()"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div style="display: flex; gap: 10px; justify-content: flex-end">
          <HButton type="primary" is-modal @click="submitSave">保存</HButton>
          <HPlainButton is-modal @click="checkWithdrawFun(1)">审核</HPlainButton>
          <HPlainButton is-modal type="error" @click="checkWithdrawFun(2)">驳回</HPlainButton>
          <HButton is-modal @click="withdrawalCheckDialog = false">关闭</HButton>
        </div>
      </template>
    </el-drawer>

    <!-- 提现单详情-->
    <el-drawer title="提现单详情" v-model="withdrawalDetailVisible" :size="1000">
      <div class="check-dialog" v-loading="loadingDetail" element-loading-text="加载中...">
        <h4 class="title_top" style="display: flex; align-items: center">
          基本信息
          <el-icon style="cursor: pointer" size="16" @click="toEdit">
            <Edit />
          </el-icon>
        </h4>

        <el-form
          label-position="right"
          :model="ruleForm"
          :data="withdrawalDetail"
          label-width="80"
          style="margin-bottom: 12px"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item label="提现单号:" prop="region">{{
                withdrawalDetail?.code
              }}</el-form-item>
              <el-form-item label="工程师:" prop="region">{{
                withdrawalDetail?.applyNetworkEmp
              }}</el-form-item>
              <el-form-item label="申请时间:" prop="region">{{
                withdrawalDetail?.createTime
              }}</el-form-item>
              <el-form-item label="申请备注:" prop="region">
                <span v-if="!isEdit">{{ withdrawalDetail?.applyRemark }}</span>
                <el-input
                  v-else
                  v-model="editForm.applyRemark"
                  maxlength="100"
                  type="textarea"
                  placeholder="请输入备注"
                  show-word-limit
                  resize="both"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="银行卡号:" prop="region">
                <span v-if="!isEdit">
                  {{ withdrawalDetail?.bankNo }}
                </span>
                <el-input v-else v-model="editForm.bankNo" placeholder="请输入"></el-input>
              </el-form-item>
              <el-form-item label="开户银行:" prop="region">
                <span v-if="!isEdit">
                  {{ withdrawalDetail?.name }}
                </span>
                <el-input v-else v-model="editForm.name" placeholder="请输入"></el-input>
              </el-form-item>
              <!-- <el-form-item label="开户行:" prop="region">{{ withdrawalDetail?.openingBank }}</el-form-item> -->

              <el-form-item label="持卡人姓名:" prop="region">
                <text v-if="!isEdit">
                  {{ withdrawalDetail?.cardholderName }}
                </text>
                <el-input v-else v-model="editForm.cardholderName" placeholder="请输入"></el-input>
              </el-form-item>
              <el-form-item label="审核备注:" prop="region">{{
                withdrawalDetail?.checkRemark
              }}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="提现状态:" prop="region">
                <HStatus type="warning" v-if="withdrawalDetail?.status === 1">提现审核</HStatus>
                <HStatus type="warning" v-if="withdrawalDetail?.status === 2">等待打款</HStatus>
                <HStatus type="success" v-if="withdrawalDetail?.status === 3">已推送银行</HStatus>
                <!-- <HStatus type="error" v-if="withdrawalDetail?.status === 4">失败</HStatus> -->
                <HStatus type="error" v-if="withdrawalDetail?.status === 5">已驳回</HStatus>
                <HStatus type="warning" v-if="withdrawalDetail?.status === 88">推送中</HStatus>
                <HStatus type="error" v-if="withdrawalDetail?.status === 99">推送失败</HStatus>
              </el-form-item>
              <el-form-item label="审核人员:" prop="region">{{
                withdrawalDetail?.checkEmp
              }}</el-form-item>
              <el-form-item label="审核时间:" prop="region">{{
                withdrawalDetail?.checkTime
              }}</el-form-item>
              <el-form-item label="打款凭证:" prop="region">
                <div
                  v-if="withdrawalDetail?.paths"
                  style="display: flex; align-items: center; gap: 10px"
                >
                  <el-image
                    v-for="(img, index) in withdrawalDetail?.paths"
                    :key="index"
                    style="width: 40px; height: 40px"
                    :src="img"
                    :zoom-rate="1.2"
                    :max-scale="7"
                    :min-scale="0.2"
                    :preview-src-list="withdrawalDetail?.paths"
                    :initial-index="index"
                    fit="cover"
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-tabs v-model="activeNameCheck" style="height: 320px">
        <el-tab-pane label="关联工单" name="first">
          <el-table
            height="240"
            :border="true"
            :summary-method="(val) => getSummaries(val, [0, 2, 3, 4, 5])"
            :data="WithdrawOrderList"
            show-summary
            resizable
            stripe
            style="margin-top: 12px"
          >
            <el-table-column
              fixed="left"
              type="index"
              align="center"
              label="序号"
              width="50"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="workNo" label="关联工单" min-width="90">
              <template v-slot="i">
                <span
                  class="xy_main_btn"
                  @click="pageGo(i.row.workId), (withdrawalDetailVisible = false)"
                  >{{ i.row.workNo }}</span
                >
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="原工单金额"
              prop="oldWithdrawMoney"
              min-width="100"
              show-overflow-tooltip
            >
              <template v-slot="i"> ￥{{ (i.row.oldWithdrawMoney || 0).toFixed(2) }} </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="修改后工单金额"
              prop="withdrawMoney"
              min-width="100"
              show-overflow-tooltip
            >
              <template v-slot="i"> ￥{{ (i.row.withdrawMoney || 0).toFixed(2) }} </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="手续费"
              prop="money"
              min-width="90"
              show-overflow-tooltip
            >
              <template v-slot="i"> ￥{{ (i.row.money || 0).toFixed(2) }} </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="实际到账"
              prop="withdrawMoney_o"
              min-width="90"
              show-overflow-tooltip
            >
              <template v-slot="i"> ￥{{ (i.row.withdrawMoney_o || 0).toFixed(2) }} </template>
            </el-table-column>
          </el-table>
          <div class="footer" style="margin-top: 12px">
            <el-pagination
              v-model:current-page="page"
              background
              v-model:page-size="size"
              :page-sizes="[10, 20, 30, 50]"
              :size="size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="WithdrawOrderList.length"
              @size-change="pageSize"
              @current-change="pageCurr"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane label="操作日志" name="second">
          <el-table
            height="240"
            :border="true"
            :data="WithdrawLogList"
            resizable
            stripe
            style="margin-bottom: 12px"
          >
            <el-table-column
              fixed="left"
              type="index"
              align="center"
              label="序号"
              width="50"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="event" label="操作内容" min-width="90">
            </el-table-column>
            <el-table-column label="操作人" prop="applyEmp" min-width="100" show-overflow-tooltip>
            </el-table-column>
            <!-- <el-table-column fixed="right" label="关联服务商" prop="network" min-width="90" show-overflow-tooltip> -->
            <!-- </el-table-column> -->
            <el-table-column
              fixed="right"
              label="备注"
              prop="remark"
              min-width="110"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作时间"
              prop="createTime"
              width="130"
              show-overflow-tooltip
            >
            </el-table-column>
          </el-table>
          <div class="footer">
            <Pagination
              ref="paginationLogRef"
              :list_total="totalLog"
              @size-change="getWithdrawLogList()"
              @current-change="getWithdrawLogList()"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div style="display: flex; gap: 10px; justify-content: flex-end">
          <HButton
            type="primary"
            is-modal
            v-loading="editLoading"
            v-if="isEdit"
            @click="editConfirm"
            >保存</HButton
          >
          <HButton is-modal @click="withdrawalDetailVisible = false">关闭</HButton>
        </div>
      </template>
    </el-drawer>
    <!-- 可提现工单 -->
    <HModal title="可提现工单" v-model="withdrawalOrderShow" :width="1000">
      <el-table
        max-height="60vh"
        @select="handleSelect"
        @select-all="selectAll"
        ref="orderListRef"
        :data="orderList"
        :border="true"
        resizable
        stripe
        style="margin: 12px 0"
      >
        <el-table-column type="selection" width="40" fixed="left" />
        <el-table-column fixed="left" type="index" label="序号" width="50" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="工单单号" prop="workNo" min-width="50" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="工单金额" min-width="50" show-overflow-tooltip>
          <template v-slot="i"> ￥{{ (i.row.totalPrice || 0).toFixed(2) }} </template>
        </el-table-column>
        <el-table-column label="完成时间" prop="endTime" min-width="50" show-overflow-tooltip>
        </el-table-column>
      </el-table>
      <div class="footer">
        <Pagination
          ref="paginationOrder"
          :list_total="totalOrder"
          @size-change="getOrderListSelect"
          @current-change="getOrderListSelect"
        />
      </div>
      <template #footerRight>
        <HButton is-modal type="primary" @click="saveConfirm">确定</HButton>
        <HButton is-modal @click="withdrawalOrderShow = false">取消</HButton>
      </template>
    </HModal>

    <!-- 批量打款弹窗 -->
    <HModal @close="changeClose" v-model="multiplePaymentModalVisible" title="批量打款" width="530">
      <el-form
        label-width="auto"
        class="modal_form_content"
        v-loading="submitLoading"
        element-loading-text="加载中..."
        label-position="top"
        inline-message
      >
        <!-- 提现单号 -->
        <!-- <el-form-item label="提现单号">
          <el-input :model-value="selectedWithdrawalList.map((item) => item.code).join('、')" />
        </el-form-item> -->

        <!-- 银行名称 -->
        <!-- <el-form-item label="银行名称">
          <el-input placeholder="请输入银行名称" />
        </el-form-item> -->

        <!-- 银行卡号 -->
        <!-- <el-form-item label="银行卡号">
          <el-input placeholder="请输入银行卡号" />
        </el-form-item> -->

        <!-- 支付凭证 -->
        <!-- <el-form-item :label="`支付凭证(${fileList.length}/4)`" v-if="withdrawVo.ids.length == 1">
          <div class="upload_img">
            <el-upload
              ref="upload"
              multiple
              :auto-upload="false"
              list-type="picture-card"
              :on-preview="lookFile"
              accept="image/*"
              drag
              action="#"
              :on-change="handleChangeImg"
              v-model:file-list="fileList"
              :limit="4"
              :on-exceed="onExceed"
            >
              <el-icon size="16">
                <Plus />
              </el-icon>
            </el-upload>
          </div>
        </el-form-item> -->

        <!-- 账户名称 -->
        <el-form-item label="账户名称"> 金华市叮咚到家智能科技有限公司 </el-form-item>

        <!-- 付款银行账号 -->
        <el-form-item label="付款银行账号"> 33050167736100000623 </el-form-item>

        <!-- 开户银行 -->
        <el-form-item label="开户银行"> 中国建设银行有限公司武义桐琴支行 </el-form-item>

        <!-- 提现单号 -->
        <el-form-item label="提现单号">
          {{ selectedWithdrawalList.map((item) => item.code).join('；') }}
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注">
          <el-input
            class="form-control"
            :rows="4"
            v-model="withdrawVo.remark"
            type="textarea"
            maxlength="100"
            placeholder="备注"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footerRight>
        <div class="dialog-footer">
          <HButton is-modal type="primary" @click="submitForm"> 确定 </HButton>
          <HButton is-modal @click="changeClose">取消</HButton>
        </div>
      </template>
    </HModal>

    <!-- 批量审核 -->
    <HModal @close="changeCloseChack" v-model="dialogChackVisible" title="批量审核" width="530">
      <el-form
        label-width="auto"
        class="save_dialog"
        v-loading="submitLoading"
        element-loading-text="加载中..."
        style="padding: 0 10px"
      >
        <el-form-item label="审核备注">
          <el-input
            class="form-control"
            :rows="4"
            v-model="checkWithdrawVo.checkRemark"
            type="textarea"
            maxlength="100"
            placeholder="备注"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footerRight>
        <div class="dialog-footer">
          <HButton is-modal @click="changeCloseChack">取消</HButton>
          <HButton is-modal type="primary" color="#007cff" @click="checkWithdrawFun(1)">
            确定
          </HButton>
        </div>
      </template>
    </HModal>
    <!-- 文件查看 -->
    <HModal title="查看" v-model="dialogContract">
      <el-image :src="`${img}`" style="max-height: 90vh"></el-image>
    </HModal>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref, reactive, onMounted, h, nextTick, watch } from 'vue'
  import { ElDivider, ElMessage } from 'element-plus'
  import { Search, RefreshRight } from '@element-plus/icons-vue'
  import type { TableInstance, UploadFile, UploadProps } from 'element-plus'
  import { useRouter } from 'vue-router'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import { HLink, HModal } from '@/components/common'
  import {
    getWithdrawList,
    saveWithdraw,
    getNetworkEmpSelect,
    getNetworkByNetworkEmpIdSelect,
    getNetworkBandSelect,
    getWithdrawHandlingFeeStrategy,
    getWithdrawOrderList,
    getWithdrawDetail,
    getWithdrawOrder,
    getWithdrawLog,
    checkWithdraw,
    finishWithdraw,
    updateWithdraw,
  } from '@/api/withdrawal'
  import _ from 'lodash'
  import { orderAnnexUpload } from '@/api/upload'
  import autoFixedDicimal from '@/utils/money'
  import useFormValidateService from '@/services/common/formValidate/useFormValidate'
  import { getNetworkPageSelect } from '@/api/network'
  import { exportWithdrawToExcel } from '@/api/upload'
  import moment from 'moment'
  import pageComponentName from '@/config/page-component-name'
  import { HMessageBox } from '@/components/common/message'

  defineOptions({
    name: pageComponentName.financialSettlement.settlementList,
  })

  /**
   * 新增提现单弹窗关闭事件
   */
  const onCloseAddWithdrawal = () => {
    withdrawalAddDialog.value = false
    if (formRef.value) {
      formRef.value.resetFields()
    }
    resetFormValidateResult()
  }

  /**
   * 使用表单验证服务
   */
  const { handleFormValidate, resetFormValidateResult, formValidateResult } =
    useFormValidateService([
      'applyNetworkEmpId',
      'cardholderName',
      'applyNetworkId',
      'name',
      'bankNo',
      'openingBank',
      'bankCode',
      'openAccountBankNetwork',
    ])

  /**
   * 间距组件的间隔符
   */
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  const router = useRouter()
  const loading = ref(false)

  // 分页组件实例
  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)

  // 表格组件实例
  const tableInstance = ref<TableInstance | null>(null)

  // 提现单列表
  const tableData = ref<Array<WithdrawalAPIResponse.ListItem>>([])

  // 提现单列表总条数
  const total = ref(0)

  /**
   * 获取体现列表请求参数
   */
  const ListData = ref<WithdrawalAPIRequest.GetListParam>({
    fieldType: 1, //字段类型：1-申请提现时间,示例值(1)
    dateType: '', //日期类型：1-今天，2-本周，3-本月，4-过去三个月，5-自定义时间区间,示例值(3)
    endTime: '', //申请提现结束时间
    keyword: '', //关键词搜索
    limit: 0,
    page: 0,
    startTime: '', //	申请提现开始时间
    workNo: '',
    engineer: '',
    networkId: '',
    status: '',
  })

  const valValue = ref()

  /**
   * 重置点击事件
   */
  const handleResetClick = () => {
    ListData.value = {
      fieldType: 1, //字段类型：1-申请提现时间,示例值(1)
      dateType: '', //日期类型：1-今天，2-本周，3-本月，4-过去三个月，5-自定义时间区间,示例值(3)
      endTime: '', //申请提现结束时间
      keyword: '', //关键词搜索
      limit: 0,
      page: 0,
      startTime: '', //	申请提现开始时间
      workNo: '',
      engineer: '', //工程师
      networkId: '',
      status: '',
    }
    getList()
  }

  const formRef = ref()
  const ruleForm = ref({
    applyNetworkEmp: '', //申请人名称
    applyNetworkEmpId: null, //申请人ID，即服务人员ID
    applyNetworkId: null, //服务商ID
    applyRemark: '', //申请备注
    bankNo: '', //银行卡号
    cardholderName: '', //持卡人姓名
    handingFeeFixedOrder: 0, //每单固定手续费：当withdrawHandlingFeeStrategy=2时生效
    handingFeeProportion: 0, //手续费比例，单位为%，当withdrawHandlingFeeStrategy=1时生效
    withdrawHandlingFeeStrategy: 1, //提现手续费策略：1-按比例收取(按提现总金额计算)，2-每间固定(按每单总金额计算),示例值(1)
    id: null,
    name: '', //银行卡名称
    openingBank: '', //开户行
    orderVos: [
      //提现工单
      // {
      //   "id": null,//提现工单ID，修改必传，新增不必传
      //   "oldWithdrawMoney": 0,//旧提现金额
      //   "remark": "",
      //   "withdrawMoney": 0,//提现金额
      //   "workId": null,//工单ID
      //   "workNo": ""//工单单号
      // }
    ],
    bankCode: '',
    openAccountBankNetwork: '',
  })
  const rules = ref({
    applyNetworkEmpId: [{ required: true, message: '申请人不能为空', trigger: ['change', 'blur'] }],
    // cardholderName: [{ required: true, message: '持卡人不能为空', trigger: ['change', 'blur'] }],
    applyNetworkId: [{ required: true, message: '服务商不能为空', trigger: ['change', 'blur'] }],
    name: [
      { required: true, message: '银行卡名称不能为空', trigger: ['change', 'blur'] },
      { required: true, max: 30, message: '银行卡名称长度限制 30', trigger: ['change', 'blur'] },
    ],
    // bankNo: [{ required: true, message: '银行卡号不能为空', trigger: ['change', 'blur'] }],
    // openingBank: [{ required: true, message: '开户行不能为空', trigger: ['change', 'blur'] }],
  })

  // 过滤状态  成功失败
  const filterTag = (value: string, row) => {
    return row.status === value
  }
  // *********** 申请提现单*****
  const withdrawalAddDialog = ref(false)
  const onCancel = () => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
    withdrawalAddDialog.value = false
    resetFormValidateResult()
  }
  const addWithdrawalShow = () => {
    withdrawalAddDialog.value = true
    ruleForm.value = {
      applyNetworkEmp: '', //申请人名称
      applyNetworkEmpId: null, //申请人ID，即服务人员ID
      applyNetworkId: null, //服务商ID
      applyRemark: '', //申请备注
      bankNo: '', //银行卡号
      cardholderName: '', //持卡人姓名
      handingFeeFixedOrder: 0, //每单固定手续费：当withdrawHandlingFeeStrategy=2时生效
      handingFeeProportion: 0, //手续费比例，单位为%，当withdrawHandlingFeeStrategy=1时生效
      withdrawHandlingFeeStrategy: 1, //提现手续费策略：1-按比例收取(按提现总金额计算)，2-每间固定(按每单总金额计算),示例值(1)
      id: null,
      name: '', //银行卡名称
      openingBank: '', //开户行
      orderVos: [],
    }
    getNetworkEmpSelectList('')
  }
  const valOld = ref('')
  watch(valOld, (n) => {
    getNetworkEmpSelectList(n)
  })
  const handleapplyNetworkEmpIdOptions = _.debounce((val) => {
    if (!val) return
    valOld.value = val.trim()
  }, 300)
  // 获取申请人列表
  const appEmpList = ref([])
  const getNetworkEmpSelectList = (val) => {
    let selectVo = {
      limit: 0,
      name: val,
      page: 0,
    }
    getNetworkEmpSelect(selectVo).then((res) => {
      if (res.data.code == 20000) {
        appEmpList.value = res.data.data.rows
      }
    })
  }
  // 申请人名称
  const onClickEmp = (item) => {
    ruleForm.value.applyNetworkEmp = item.name
    getNetworkByNetworkEmpIdSelectList(item.id)
  }
  // *********根据服务人员获取下拉数据******************
  const networkList = ref([])
  const getNetworkByNetworkEmpIdSelectList = (id) => {
    getNetworkByNetworkEmpIdSelect(id).then((res) => {
      if (res.data.code == 20000) {
        networkList.value = res.data.data.rows
        if (res.data.data.rows.length == 1) {
          ruleForm.value.applyNetworkId = networkList.value[0].id
        }
      }
    })
  }
  // *********************获取银行卡****************
  const bankCardList = ref([])
  const visibleSearchBank = ref(false)
  const getNetworkBandSelectList = () => {
    if (!ruleForm.value.applyNetworkEmpId) return
    getNetworkBandSelect(ruleForm.value.applyNetworkEmpId).then((res) => {
      if (res.data.code === 20000) {
        bankCardList.value = res.data.data.rows
        res.data.data.rows.length == 0
          ? (visibleSearchBank.value = false)
          : (visibleSearchBank.value = true)
      }
    })
  }
  // 选择银行卡
  const changebankCardItem = (item) => {
    ruleForm.value.name = item.name
    ruleForm.value.bankNo = item.code
    ruleForm.value.cardholderName = item.cardholderName
    console.log(item)
    ruleForm.value.bankCode = item.bankCode
    ruleForm.value.openAccountBankNetwork = item.openAccountBankNetwork
    visibleSearchBank.value = false
  }
  // 关联服务商变化
  const networkChange = (id) => {
    if (id) getWithdrawHandlingFeeStrategyObj(id)
  }
  // ************根据服务商ID获取提现策略***************
  const getWithdrawHandlingFeeStrategyObj = (id) => {
    getWithdrawHandlingFeeStrategy(id).then((res) => {
      ruleForm.value.handingFeeFixedOrder = res.data.data.row.handingFeeFixedOrder
      ruleForm.value.withdrawHandlingFeeStrategy = res.data.data.row.withdrawHandlingFeeStrategy
      ruleForm.value.handingFeeProportion = res.data.data.row.handingFeeProportion
    })
  }
  // ******审核提现单************
  const activeNameCheck = ref('first')
  const withdrawalCheckDialog = ref(false)
  const checkWithdrawVo = ref({
    checkRemark: '',
    result: 1, //审核结果：1-审核通过，2-驳回,示例值(1)
    ids: [],
  })

  /**
   * 审核点击事件
   * @param id - 提现单id
   */
  const handleCheckClick = (id: string) => {
    activeNameCheck.value = 'first'
    checkWithdrawVo.value.ids = [id]
    getWithdrawDetailObj(id)
    withdrawalCheckDialog.value = true
  }

  // 批量审核
  const dialogChackVisible = ref(false)
  const changeCloseChack = () => {
    checkWithdrawVo.value.checkRemark = ''
    dialogChackVisible.value = false
  }
  const dialogChackVisibleShow = () => {
    checkWithdrawVo.value.checkRemark = ''
    dialogChackVisible.value = true
  }
  const checkWithdrawFun = (val) => {
    checkWithdrawVo.value.result = val
    checkWithdraw(checkWithdrawVo.value).then((res) => {
      if (res.data.success) {
        checkWithdrawVo.value.checkRemark = ''
        checkWithdrawVo.value.ids = []
        withdrawalCheckDialog.value = false
        dialogChackVisible.value = false
        getList()
      }
      if (res.data.isError)
        ElMessage({
          message: res.data.message,
          type: res.data.success ? 'success' : 'error',
          duration: 2000,
        })
    })
  }

  // 合计
  const getSummaries = (param, arr = []) => {
    const { columns, data } = param
    const sums: string[] = []
    columns.forEach((column, index) => {
      if (arr.includes(index) && (index == 1 || index == 0)) {
        sums[index] = '合计'
        return
      }
      const values = data.map((item) => Number(item[column.property]))
      if (!values.every((value) => Number.isNaN(value))) {
        if (arr.includes(index)) {
          sums[index] = `￥${values
            .reduce((prev, curr) => {
              const value = Number(curr)
              if (!Number.isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            .toFixed(2)}`
        }
      } else {
        sums[index] = ''
      }
    })
    return sums
  }
  // **********
  const networkSelectData = ref([])
  // 获取服务商下拉数据
  const getNetworkPageSelectData = (val) => {
    const networkSearch = {
      name: val, // 服务商名称
      page: 1,
      limit: 100,
    }
    networkSelectData.value = []
    getNetworkPageSelect(networkSearch).then((res) => {
      networkSelectData.value = res.data.data.rows
    })
  }
  const secVo = ref('')
  const getNetworkPageSelectList = (val) => {
    secVo.value = val
  }
  watch(secVo, (n) => {
    getNetworkPageSelectData(n)
  })
  // *********提现详情***********
  const withdrawalDetailVisible = ref(false)
  const withdrawalDetail = ref()
  const loadingDetail = ref(false)
  const withdrawalDetailShow = (id) => {
    activeNameCheck.value = 'first'
    getWithdrawDetailObj(id)
    withdrawalDetailVisible.value = true
    isEdit.value = false
  }
  const getWithdrawDetailObj = async (id) => {
    loadingDetail.value = true
    await getWithdrawDetail(id).then(async (res) => {
      if (res.data.success) {
        withdrawalDetail.value = res.data.data.row
        await getOrderList(res.data.data.row.id)
      } else {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: 'error',
            duration: 2000,
          })
      }
      loadingDetail.value = false
    })
  }
  watch(activeNameCheck, (n) => {
    switch (n) {
      case 'first':
        break
      case 'second':
        getWithdrawLogList()
        break
    }
  })
  // 根据id获取详情关联工单
  const WithdrawOrderList = ref([])
  const getOrderList = async (id) => {
    await getWithdrawOrder(id).then((res) => {
      if (res.data.success) {
        WithdrawOrderList.value = res.data.data.rows.map((o) => {
          let money = 0
          if (withdrawalDetail.value.withdrawHandlingFeeStrategy == 1) {
            money = Number(
              (withdrawalDetail.value.handingFeeProportion * 0.01 * o.withdrawMoney || 0).toFixed(
                2,
              ),
            )
          } else {
            money = withdrawalDetail.value.handingFeeFixedOrder
          }
          let rowVo = {
            id: o.id, //提现工单ID，修改必传，新增不必传
            oldWithdrawMoney: o.oldWithdrawMoney, //旧提现金额
            remark: o.remark,
            money: money,
            withdrawMoney: o.withdrawMoney || 0, //提现金额
            withdrawMoney_o: parseFloat((o.withdrawMoney - money).toFixed(2)),
            workId: o.workId, //工单ID
            workNo: o.workNo, //工单单号
          }
          return rowVo
        })

        ruleForm.value = {
          applyNetworkEmp: withdrawalDetail.value.applyNetworkEmp, //申请人名称
          applyNetworkEmpId: withdrawalDetail.value.applyNetworkEmpId, //申请人ID，即服务人员ID
          applyNetworkId: withdrawalDetail.value.applyNetworkId, //服务商ID
          applyRemark: withdrawalDetail.value.applyRemark, //申请备注
          bankNo: withdrawalDetail.value.bankNo, //银行卡号
          cardholderName: withdrawalDetail.value.cardholderName, //持卡人姓名
          handingFeeFixedOrder: withdrawalDetail.value.handingFeeFixedOrder, //每单固定手续费：当withdrawHandlingFeeStrategy=2时生效
          handingFeeProportion: withdrawalDetail.value.handingFeeProportion, //手续费比例，单位为%，当withdrawHandlingFeeStrategy=1时生效
          withdrawHandlingFeeStrategy: withdrawalDetail.value.withdrawHandlingFeeStrategy, //提现手续费策略：1-按比例收取(按提现总金额计算)，2-每间固定(按每单总金额计算),示例值(1)
          id: withdrawalDetail.value.id,
          name: withdrawalDetail.value.name, //银行卡名称
          openingBank: withdrawalDetail.value.openingBank, //开户行
          orderVos: WithdrawOrderList.value,
        }
      } else {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: 'error',
            duration: 2000,
          })
      }
    })
  }
  // 根据id获取操作日志
  const paginationLogRef = ref()
  const totalLog = ref(0)
  const WithdrawLogList = ref([])
  const getWithdrawLogList = () => {
    let pagesVo = {
      limit: paginationLogRef.value.size,
      page: paginationLogRef.value.current,
    }
    getWithdrawLog(pagesVo, withdrawalDetail.value.id).then((res) => {
      if (res.data.success) {
        WithdrawLogList.value = res.data.data.rows
        totalLog.value = Number(res.data.data.total || 0)
      } else {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: 'error',
            duration: 2000,
          })
      }
    })
  }
  // ************修改提现单***********
  const withdrawalEditVisible = ref(false)
  const withdrawalEdit = async (id) => {
    activeNameCheck.value = 'first'
    withdrawalEditVisible.value = true
    getWithdrawDetailObj(id)
  }
  // 输入值变价
  const changeInput = (row) => {
    row.withdrawMoney_o = parseFloat((row.withdrawMoney - row.money).toFixed(2))
  }
  // 关联工单详情
  const pageGo = (id: string) => {
    router.push('/order/odetail/' + id)
  }
  // 报单时间
  const timeOptions = ref([
    { title: '今天', value: 1 },
    { title: '本周', value: 2 },
    { title: '本月', value: 3 },
    { title: '过去三个月', value: 4 },
    { title: '时间区间', value: 5 },
  ])

  /**
   * 获取提现单列表
   */
  const getList = async () => {
    if (!paginationInstance.value) return false
    try {
      ListData.value.limit = paginationInstance.value.size
      ListData.value.page = paginationInstance.value.current
      loading.value = true
      const res = await getWithdrawList({ ...ListData.value, status: activeName.value })
      loading.value = false
      if (res.data.code === 20000) {
        tableData.value = res.data.data.rows
        total.value = Number(res.data.data.total) || 0
        return
      }

      HMessageBox.error(res.data.message)
    } catch (error) {
      loading.value = false
    }
  }

  // 时间变化时
  const dateChange = (val: any) => {
    if (val) {
      // popoverDom1.value.hide()
      ListData.value.startTime = val[0]
      ListData.value.endTime = val[1]
    } else {
      ListData.value.startTime = null
      ListData.value.endTime = null
    }
    getList()
  }

  // 获取可提现工单列表
  const withdrawalOrderShow = ref(false)
  const paginationOrder = ref() //ref元素
  const totalOrder = ref(0)
  const orderList = ref([])
  const orderListRef = ref()
  const orderVosList = ref([]) //已选择的工单
  const onShowUpgrade = async () => {
    if (!ruleForm.value.applyNetworkEmpId) {
      ElMessage({
        type: 'warning',
        message: '请先选择工程师！',
      })
      return
    }
    if (!ruleForm.value.applyNetworkId) {
      ElMessage({
        type: 'warning',
        message: '请先选择关联服务商！',
      })
      return
    }

    if (ruleForm.value.applyNetworkId && ruleForm.value.applyNetworkEmpId) {
      withdrawalOrderShow.value = true
      nextTick(() => {
        orderVosList.value = _.cloneDeep(ruleForm.value.orderVos)
        getOrderListSelect()
      })
    }
  }
  // 提现导出
  const onShowExport = async () => {
    if (tableData.value.length == 0) {
      ElMessage({
        type: 'warning',
        message: '暂无数据导出',
      })
      return
    }
    const res = await exportWithdrawToExcel(ListData.value)
    if (res.data.isError)
      ElMessage({
        type: res.data.code && !res.data.success ? 'error' : 'success',
        message: res.data.code && !res.data.success ? res.data.message : '提现单数据导出成功',
      })
    if (res.data.code && !res.data.success) {
      return
    }
    const url = window.URL.createObjectURL(new Blob([res.data], { type: '.xlsx' }))
    const link = document.createElement('a')
    link.href = url
    link.download = `提现单数据_${moment(new Date()).format('YYYYMMDD')}.xlsx`
    link.click()
  }
  // 请求获取可提现列表
  const getOrderListSelect = async () => {
    let pagesObj = {
      limit: paginationOrder.value.size,
      page: paginationOrder.value.current,
    }
    await getWithdrawOrderList(
      pagesObj,
      ruleForm.value.applyNetworkId,
      ruleForm.value.applyNetworkEmpId,
    ).then((res) => {
      totalOrder.value = Number(res.data.data.total)
      orderList.value = res.data.data.rows
      setOrderSelect()
    })
  }
  // 设置渲染回显
  const setOrderSelect = () => {
    orderVosList.value.map((item) => {
      orderList.value.filter((item2) => {
        if (item.workId === item2.id) {
          nextTick(() => {
            orderListRef.value!.toggleRowSelection(item2, true)
          })
        }
      })
    })
  }
  // 获取选择的可提现列表
  const handleSelect = (val, row: any) => {
    let result = val.some((item) => item.id == row.id) //判断是否是 选中
    let idSelsctId = orderVosList.value.filter((item) => item.id == row.id)[0]?.id || ''
    if (result) {
      let money = 0
      if (ruleForm.value.withdrawHandlingFeeStrategy == 1) {
        money = Number(
          (ruleForm.value.handingFeeProportion * 0.01 * row.totalPrice || 0).toFixed(2),
        )
      } else {
        money = ruleForm.value.handingFeeFixedOrder
      }
      let rowVo = {
        id: idSelsctId, //提现工单ID，修改必传，新增不必传
        oldWithdrawMoney: row.totalPrice, //旧提现金额
        remark: '',
        money: money,
        withdrawMoney: parseFloat((row.totalPrice - money || 0).toFixed(2)), //提现金额
        workId: row.id, //工单ID
        workNo: row.workNo, //工单单号
      }
      orderVosList.value.push(rowVo)
    } else {
      orderVosList.value = orderVosList.value.filter((o) => o.id != row.id)
    }
  }
  // 列表全部 勾选or取消
  const selectAll = (val) => {
    if (val.length > 0) {
      val.map((row) => {
        let result = orderVosList.value.some((item) => item.id == row.id) //判断是否是 选中
        let idSelsctId = orderVosList.value.filter((item) => item.id == row.id)[0]?.id || ''
        let money = 0
        if (ruleForm.value.withdrawHandlingFeeStrategy == 1) {
          money = Number((ruleForm.value.handingFeeProportion * row.totalPrice || 0).toFixed(2))
        } else {
          money = ruleForm.value.handingFeeFixedOrder
        }
        let rowVo = {
          id: idSelsctId, //提现工单ID，修改必传，新增不必传
          oldWithdrawMoney: row.totalPrice, //旧提现金额
          remark: '',
          money: money,
          withdrawMoney: parseFloat((row.totalPrice - money || 0).toFixed(2)), //提现金额
          workId: row.id, //工单ID
          workNo: row.workNo, //工单单号
          endTime: row.endTime,
        }
        if (!result) {
          orderVosList.value.push(rowVo)
        }
      })
    } else if (val.length == 0) {
      orderList.value.map((row) => {
        orderVosList.value = orderVosList.value.filter((o) => o.goodsSpecId != row.specId)
      })
    }
  }
  // 删除
  const deleteItem = (row) => {
    ruleForm.value.orderVos = ruleForm.value.orderVos.filter((o) => !(o.workId == row.workId))
  }
  // 确定选择
  const saveConfirm = () => {
    ruleForm.value.orderVos = _.cloneDeep(orderVosList.value)
    withdrawalOrderShow.value = false
  }
  // 提交保存请求
  const saveLoading = ref(false)
  const submitSave = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async (val) => {
      if (val) {
        if (ruleForm.value.orderVos.length == 0) {
          ElMessage({
            message: '请选择可提现工单',
            type: 'warning',
            duration: 2000,
            offset: 300,
          })
          return
        }
        saveLoading.value = true
        let dataObj = _.cloneDeep(ruleForm.value)
        dataObj.orderVos = dataObj.orderVos.map((o) => {
          return o
        })
        await saveWithdraw(dataObj).then(async (res) => {
          if (res.data.isError)
            ElMessage({
              message: res.data.message,
              type: res.data.success ? 'success' : 'error',
              duration: 2000,
            })
          if (res.data.code == 20000) {
            await formRef.value.resetFields()
            ruleForm.value.orderVos = []
            withdrawalAddDialog.value = false
            withdrawalCheckDialog.value = false
            getList()
          }
          saveLoading.value = false
        })
      }
    })
  }
  const page = ref()
  const size = ref()
  const pageCurr = (val) => {
    page.value = val
  }
  const pageSize = (val) => {
    size.value = val
  }
  const withdrawVo = ref({
    ids: [], //提现单ID
    paths: [], //提现凭证，只有单个提现单时，此字段生效，多个提现单不允许上传凭证
    remark: '', //备注
  })

  // 批量打款弹窗显示状态
  const multiplePaymentModalVisible = ref(false)

  // 选择的提现单列表
  const selectedWithdrawalList = ref<Array<WithdrawalAPIResponse.ListItem>>([])

  /**
   * 表格选择事件
   * @param val - 选择的行
   */
  function handleTableSelect(val: Array<WithdrawalAPIResponse.ListItem>) {
    withdrawVo.value.ids = []
    val.filter((o) => {
      withdrawVo.value.ids.push(o.id)
    })

    selectedWithdrawalList.value = val
  }

  /**
   * 批量打款点击事件
   */
  const handleMultiplePaymentClick = () => {
    multiplePaymentModalVisible.value = true
    checkWithdrawVo.value.ids = withdrawVo.value.ids
  }

  /**
   * 打款点击事件
   * @param item
   */
  const handlePaymentClick = (item: WithdrawalAPIResponse.ListItem) => {
    if (tableInstance.value) {
      tableInstance.value.clearSelection()
      handleMultiplePaymentClick()
      tableInstance.value.toggleRowSelection(item, true)
    }
  }

  // 查看图片
  const img = ref('')
  const dialogContract = ref(false)
  const lookFile = (val) => {
    img.value = val.url || val
    dialogContract.value = true
  }
  // 确定
  const submitLoading = ref(false)
  const fileList = ref([])
  // 获取图片
  const handleChangeImg: UploadProps['onChange'] = (uploadFile: UploadFile, uploadFiles) => {
    fileList.value = uploadFiles
  }
  // 覆盖上一张
  const upload = ref()
  const onExceed: UploadProps['onExceed'] = (files) => {
    // upload.value!.clearFiles()
    // const file = files[0] as UploadRawFile
    // file.uid = genFileId()
    // upload.value!.handleStart(file)
    ElMessage({
      message: '最多上传4张',
      type: 'error',
    })
  }
  const submitForm = _.debounce(async () => {
    if (fileList.value.length > 0) {
      let imgs = fileList.value.map((o) => o.raw)
      await orderAnnexUpload(imgs).then((res) => {
        if (res.data.success) {
          withdrawVo.value.paths = res.data.data.rows
        }
      })
    }
    await finishWithdraw(withdrawVo.value).then((res) => {
      if (res.data.success) {
        fileList.value = []
        withdrawVo.value.paths = []
        withdrawVo.value.remark = ''
        multiplePaymentModalVisible.value = false
        getList()
      }
      ElMessage({
        message: res.data.success ? '批量打款成功！' : res.data.message,
        type: res.data.success ? 'success' : 'error',
      })
    })
    submitLoading.value = false
  }, 800)
  const changeClose = () => {
    fileList.value = []
    withdrawVo.value.paths = []
    withdrawVo.value.remark = ''
    multiplePaymentModalVisible.value = false
  }

  const activeName = ref('')
  // 1-提现待审核，2-付款中/等待打款，3-打款完成，4-失败，5-驳回
  const tabPanes = reactive([
    {
      label: '全部',
      value: '',
    },
    {
      label: '提现待审核',
      value: '1',
    },
    {
      label: '付款中/等待打款',
      value: '2',
    },
    {
      label: '已推送银行',
      value: '3',
    },
    // {
    //   label: '失败',
    //   value: '4',
    // },
    {
      label: '驳回',
      value: '5',
    },
    {
      label: '推送中',
      value: '88',
    },
    {
      label: '推送失败',
      value: '99',
    },
  ])

  const tabClick = (val) => {
    activeName.value = val
    ListData.value.status = val
    getList()
  }

  const editLoading = ref(false)
  const editForm = ref({
    bankNo: '',
    name: '',
    cardholderName: '',
    applyRemark: '',
  })
  const isEdit = ref(false)
  const toEdit = () => {
    isEdit.value = true
    Object.assign(editForm.value, {
      bankNo: withdrawalDetail.value.bankNo,
      name: withdrawalDetail.value.name,
      cardholderName: withdrawalDetail.value.cardholderName,
      applyRemark: withdrawalDetail.value.applyRemark,
    })
  }

  // 编辑修改
  const editConfirm = async () => {
    if (!editForm.value.bankNo) {
      ElMessage({
        message: '请输入银行卡号',
        type: 'error',
        duration: 2000,
      })
      return
    }
    if (!editForm.value.name) {
      ElMessage({
        message: '请输入开户银行',
        type: 'error',
        duration: 2000,
      })
      return
    }
    if (!editForm.value.cardholderName) {
      ElMessage({
        message: '请输入持卡人姓名',
        type: 'error',
        duration: 2000,
      })
      return
    }
    editLoading.value = true
    const res = await updateWithdraw(withdrawalDetail.value.id, editForm.value)
    editLoading.value = false
    if (res.data.isError) {
      ElMessage({
        message: res.data.message,
        type: res.data.success ? 'success' : 'error',
        duration: 2000,
      })
    }
    if (res.data.code == 20000) {
      withdrawalCheckDialog.value = false
      getList()
      isEdit.value = false
      withdrawalDetailVisible.value = false
    }
  }

  onMounted(() => {
    getList()
    getNetworkPageSelectData('')
  })
</script>

<style scoped lang="scss">
  @import './index.scss';

  .nav {
    width: 100%;
    border-radius: 2px;
    background: #ffffff;
    padding: 0 12px;
    box-sizing: border-box;
    margin-bottom: 12px;
  }

  .demo-tabs {
    :deep(.el-tabs__header) {
      margin: 0 0 8px !important;

      .el-tabs__nav-wrap {
        .el-tabs__nav {
          .el-tabs__item.is-top:nth-child(2) {
            padding-left: 0;
          }
        }
      }
    }

    :deep(.el-tabs__nav-wrap::after) {
      height: 1px;
    }
  }

  .save_dialog {
    .el-form-item {
      display: flex;
      align-items: center;

      & ~ .el-form-item {
        margin-top: 20px;
      }
    }
  }

  .dialog-footer {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  :deep(.upload_img) {
    width: 100%;

    .el-upload-list--picture-card {
      display: flex;
      flex-wrap: wrap;
      // flex-direction: row-reverse;
      justify-content: left;

      .el-upload {
        width: 60px;
        height: 60px;
        // margin: 8px 0 0 8px;
        background-color: #fff;
      }

      .el-upload-list__item {
        width: 60px;
        height: 60px;
        // margin: 8px 0 0 8px;

        .el-upload-list__item-actions {
          font-size: 16px;

          &:hover {
            display: flex;
            justify-content: space-around;
            align-items: center;
          }
        }
      }
    }

    .el-upload-dragger {
      padding: 0;
      height: 100%;
      border: none !important;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
</style>
<style lang="scss">
  .el-popover.monitor-yt-popover {
    padding: 6px 0;

    .user_item {
      font-size: 12px;
      margin: 0 6px;
      padding: 4px 0;
      cursor: pointer;
      display: flex;
      align-items: center;
      flex-wrap: nowrap;

      &:hover {
        background-color: rgb(245, 247, 250);
      }
    }
  }
</style>
